package com.midea.thread;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

public class TestForkJoinSort {
    public static void main(String[] args) {
        Random random = new Random();
        int[] data = new int[5000000];
        for (int i = 0 ; i< data.length;i++){
            data[i] = random.nextInt(5000000);
        }

        ForkJoinPool pool = new ForkJoinPool();
        MySortTask main = new MySortTask(data,0,data.length);
        pool.invoke(main);
        for (int i = 0;i<100;i++){
            System.out.println(data[i]);
        }
    }
}
class MySortTask extends RecursiveAction{
    int[] data;
    int start;//包含起始下标
    int end;//不包含结束下标
    public final int THRESHOLD = 1000;
    public MySortTask(int[] data,int start,int end){
        super();
        this.data = data;
        this.start = start;
        this.end = end;
    }
    @Override
    protected void compute() {
        if (end -start <= THRESHOLD){
            Arrays.sort(data,start,end);
        }else{
            int middle = (start+end)/2;
            MySortTask task1 = new MySortTask(data,start,middle);
            MySortTask task2 = new MySortTask(data,middle,end);
            invokeAll(task1,task2);
            merge(middle);
        }
    }

    //将两个有序的小数组合并成有序的大数组
    private void merge(int middle) {
        int x = 0;//数组a的计数器
        int y = 0;//数组b的计数器
        int[] a = Arrays.copyOfRange(data,start,middle);
        int[] b = Arrays.copyOfRange(data,middle,end);
        for (int i = start;i < end;i++){
           /* if (x==a.length){
                data[i] = b[y];
                y++;
            }else if (y==a.length){
                data[i] = a[x];
                x++;
            }else if (a[x]<b[y]) {
                data[i] = a[x];
                x++;
            }else {
                data[i] = b[y];
                y++;
            }*/

            if (x==a.length) {
                data[i] = b[y++];
            } else if (y==a.length) {
                data[i] = a[x++];
            } else if (a[x]<b[y]) {
                data[i] = a[x++];
            } else {
                data[i] = b[y++];
            }

        }
    }

}